package com.luosonxin.controller;

import com.luosonxin.bean.User;
import com.luosonxin.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @RequestMapping("/login")
    public String login(@Valid User user, Model model, HttpSession session){
        Map<String,Object> map=userService.userLogin(user);
        System.out.println(map);
        if (map.get("user")!=null){
            session.setAttribute("userLogin",map.get("user"));
            return "redirect:/books";
        }
        model.addAttribute("msg",map.get("msg"));
        return "forward:/login.jsp";
    }
    @RequestMapping("/register")
    public String register(MultipartFile avatar, @Valid User user, Date birthday, Model model, BindingResult bindingResult ){
        user.setBirthday(birthday);
        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            Map<String, String> map = new HashMap<>();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            model.addAttribute("errors", map);
            return "forward:/register.jsp";
        }
        int i = userService.insertUser(user);
        if (i==-1){
            model.addAttribute("msg", "用户名已经存在");
            return "forward:/register.jsp";
        }
        if(avatar != null && !avatar.isEmpty() && avatar.getContentType().contains("image")){
            System.out.println("上传文件");
            try {
                String fileName = avatar.getOriginalFilename();
                String newFileName = System.currentTimeMillis()+fileName;
                String savePath = "c:/headImage/"+newFileName;//确定 文件存储的路径
                System.out.println(savePath);
                String visitPath = "/luosonxin/headImage/"+newFileName;
                avatar.transferTo(new File(savePath));
                userService.updateHeadImage(visitPath,user.getUsername());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("msg", "注册成功");
        return "forward:/index.jsp";
    }
}
